package com.cheer.log;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.cheer.service.AuthService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 统一日志处理切面
 *
 * @author cheer
 */
@Aspect
@Component
@Order(1)
public class WebLogAspect {

    private static final Logger LOGGER = LoggerFactory.getLogger(WebLogAspect.class);

    @Autowired
    private ObjectMapper objectMapper;

    @Pointcut("execution(public * com.cheer.controller.*.*(..))")
    public void webLog() {
    }

    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        WebLog webLog = new WebLog();
        webLog.setUrl(request.getRequestURL().toString());

        DateTime startTime = DateUtil.date();
        webLog.setStartTime(DateUtil.formatDateTime(startTime));

        try {
            Object result = joinPoint.proceed();
            webLog.setResult("success");
            webLog.setSpendTime((DateUtil.betweenMs(startTime, DateUtil.date()) + "毫秒"));
            LOGGER.info(objectMapper.writeValueAsString(webLog));
            return result;
        } catch (Throwable e) {
            webLog.setResult("fail");
            webLog.setSpendTime((DateUtil.betweenMs(startTime, DateUtil.date()) + "毫秒"));
            webLog.setException(e.getMessage());
            LOGGER.error(objectMapper.writeValueAsString(webLog));
            throw e;
        }
    }
}
